package com.ledou44.ledousrad.service;

import com.ledou44.ledousrad.LedouSradBeanFactory;
import com.ledou44.ledousrad.dto.LedouSradDTO;
import com.ledou44.ledousrad.dto.ServiceDTO;
import com.ledou44.ledousrad.sradenum.DiscoveryResultEnum;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author ledou44
 * 处理服务发现相关业务
 */
public class DiscoveryService {

    /**
     * 获取服务
     * @param ledouSradDTO 服务名
     * @return 服务信息
     */
    public static LedouSradDTO getService(LedouSradDTO ledouSradDTO) {
        LedouSradDTO result = new LedouSradDTO();
        String serviceName = ledouSradDTO.getServiceName();
        List<ServiceDTO> serviceList = LedouSradBeanFactory.serviceBean.get(serviceName);
        if(CollectionUtils.isEmpty(serviceList)) {
            result.setDiscoveryResult(DiscoveryResultEnum.NOT_FOUND.getCode());
            return result;
        }
        //随机调用一个微服务的实现类
        int size = serviceList.size();
        int index = (int) Math.floor(Math.random()*100 % size);
        result.setDiscoveryResult(DiscoveryResultEnum.SUCCESS.getCode());
        result.setService(serviceList.get(index));
        return result;
    }

}
